
package com.joysuch.wwyt.dataperm.context;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class DataPermRegisterInfoContext {

    private static Map<String, List<DataPermRegisterInfo>> map = new HashMap<>();

    public static void add(DataPermRegisterInfo info) {
        String table = removeWrappingQuote(info.getTableName().toLowerCase());
        List<DataPermRegisterInfo> list = map.get(table);
        if (list == null) {
            list = new ArrayList<>();
            map.put(table, list);
        }
        list.add(info);
    }

    public static void addInfo(String table, String column, String fieldName, Class entityClass) {
        table = removeWrappingQuote(table.toLowerCase());
        DataPermRegisterInfo info = new DataPermRegisterInfo();
        info.setEntityClass(entityClass);
        info.setFieldName(fieldName);
        info.setSqlColumn(column);
        info.setTableName(table);
        add(info);
    }

    public static DataPermRegisterInfo getInfo(String table, String column) {
        table = removeWrappingQuote(table.toLowerCase());
        List<DataPermRegisterInfo> list = map.get(table);
        if (list != null) {
            return list.stream().filter(e -> e.getSqlColumn().equals(column)).findFirst().orElse(null);
        }
        return null;
    }

    public static List<DataPermRegisterInfo> getInfo(String table) {
        table = removeWrappingQuote(table.toLowerCase());
        return map.get(table);
    }

    public static void removeInfo(String table) {
        map.remove(table);
    }

    private static String createKey(String table, String column) {
        return table + "." + column;
    }

    private static String removeWrappingQuote(String table) {
        // 移除部分sql带有的反引号
        return table.replace("`", "");
    }

}
